package com.shenxuchen.crm.web.advice;

import com.shenxuchen.crm.exception.CRMException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice // 对控制器进行增强
public class MyExceptionHandler {

    private Map handler(HttpServletRequest request, HttpServletResponse response, String errMsg) throws IOException {
        Boolean isAjax = request.getHeader("X-Requested-With") != null;
        if (isAjax) {
            return new HashMap() {{
                put("success", false);
                put("message", errMsg);
            }};
        } else {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<script>alert('" + errMsg + "');history.back();</script>");
            return null;
        }
    }

    // 仅处理 CRMException 异常
    @ExceptionHandler(CRMException.class)
    @ResponseBody
    public Map crmException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        e.printStackTrace();// 打印异常信息
        return handler(request, response, e.getMessage());
    }

    // 处理其它异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map otherException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        e.printStackTrace(); // 打印异常信息
        return handler(request, response, "系统忙，请稍后再试...");
    }
}
